package com.zjh.selectsort;

import java.util.Arrays;

/**
 * Created by zjh on 2017/9/30.
 */
public class SelectionSort {

    public static void swapElement(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    public static int indexLowest(int[] array, int start) {
        int lowIndex = start;
        for (int i = start; i < array.length; i++) {
            if (array[i] < array[lowIndex]) {
                lowIndex = i;
            }
        }
        return lowIndex;
    }

    private static int indexMax(int[] array, int start) {
        int maxIndex = start;
        for (int i = start; i < array.length; i++) {
            if (array[maxIndex] < array[i]) {
                maxIndex = i;
            }
        }
        return maxIndex;
    }

    public static void selectionSort(int[] array,int type) {
        for (int i = 0; i < array.length; i++) {
            if (type == 1) {
                //找出从i开始最小的元素的序号
                int j = indexLowest(array, i);
                //将第i个和从i开始的最小元素交换
                swapElement(array, i, j);
            }else {
                int j = indexMax(array, i);
                swapElement(array, i, j);
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {3, 2, 4, 55, 66, 11, 45, 21};
        selectionSort(array,1);
        System.out.println(Arrays.toString(array));
        selectionSort(array, 2);
        System.out.println(Arrays.toString(array));

    }

}
